package com.meitianhui.convenitenbuy.http.interceptor;

import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.UserToken;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.SystemUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * A interceptor to add User-Agent in header.
 * Created by Liam on 2018/5/7.
 */
public final class UserAgentInterceptor implements Interceptor {

    private static final String USER_AGENT = "UserAgent";
    private static String sDeviceModel = null;
    private static String sVersionName = null;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Request request = originalRequest.newBuilder()
                .header("User-Agent", getUserAgent())
                .header(USER_AGENT, getUserAgent())
                .build();

        return chain.proceed(request);
    }

    private String getUserAgent() {
        if (EmptyUtil.isEmpty(sDeviceModel)) {
            sDeviceModel = SystemUtils.getDeviceModel();
        }
        if (EmptyUtil.isEmpty(sVersionName)) {
            sVersionName = SystemUtils.getVersionName(App.getInstance());
        }

        UserToken userToken = InfoProvider.getUserToken(App.getInstance());
        String memberId = userToken == null ? "" : userToken.getMember_id();

        return "User-Agent Android" + "|" + sDeviceModel + "|" + sVersionName + "|" + memberId;
    }

}
